<?php
/*
===========================================================================

  Copyright (c) 2010-2012 DSPWeb Development Team

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see http://www.gnu.org/licenses/

  This file is part of DSPWeb source code

===========================================================================
*/

if (ini_get('sessions.auto_start') != 1) {
	session_start();
}
include("sql.php");
include("config.php");
include("functions.php");

$sql = new SQL;
$sql->connect($dbhost,$dbuser,$dbpass,$dbname);

if (!empty($_SESSION['loggedin'])) {	
	header("Location: index.php");
}
else {

	if (!$enable_registration) {
		$error = "Registration disabled. Please contact a server administrator to create an account!";
	}
	else {
		if (!empty($_POST['register'])) {
			if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['confpass'])) {
				$error = "One or more fields were left blank!";
			}
			else {
				$username = $sql->smartquote($_POST['username']);
				$pass = $sql->smartquote($_POST['password']);
				$cfpass = $sql->smartquote($_POST['confpass']);
				
				if ($pass != $cfpass) {
					$error = "Your passwords do not match!";
				}
				else {
					$query = $sql->query("SELECT * FROM accounts WHERE login='$username'");
					if ($sql->num_rows($query) != 0) {
						$error = "Username is already in use. Please choose another.";
					}
					else {
						$time = date('Y-m-d H:i:s',time());
						$query = $sql->query("SELECT MAX(id) FROM accounts");
						$res = $sql->fetch_assoc($query);
						if ($res['MAX(id)'] == null) {
							$id = 1000;
						}
						else {
							$id = $res['MAX(id)'];
							$id++;
						}
						
						if (!$sql->query("INSERT INTO accounts (`id`,`login`,`password`,`timecreate`,`timelastmodify`,`content_ids`,`status`,`priv`) VALUES ('$id','$username',PASSWORD('$pass'),'$time','$time','16','1','1')")) {
							$error = "A problem was encountered when creating your account. Please try again!";
						}
						else {
							$_SESSION['loggedin'] = $username;
							$_SESSION['login'] = $username;
							$success = "Your account was created successfully. <a href=\"index.php\">Continue</a>";
						}
					}
				}
			}
		}
	}
	
	$page = "views/register.php";
	include_once("template.php");
	echo $output;
}

$sql->close();
?>